import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getRecharge, createRecharge, updateRecharge, deleteRecharge } from './recharge.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  const data = await getRecharge();
  response.send(data);
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  const { howMany, phoneNumber } = request.body;

  // 创建
  try {
    const data = await createRecharge({ howMany, phoneNumber });
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 获取更新内容
  const post = _.pick(request.body, ['howMany', 'phoneNumber']);

  // 更新
  try {
    const data = await updateRecharge(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.params;

  // 删除
  try {
    const data = await deleteRecharge(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}
